<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller as BaseController;
use App\Http\Requests\ApplicationRequest;
use App\Http\Responses\CustomResponse;
use App\Services\admin\ApplicationService;
use App\Services\common\SysMapService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;

/**
 * 应用管理
 * User: zhx
 * Date: 2023/10/27 0027
 * Time: 14:48
 */
class ApplicationController extends BaseController
{
    /**
     * 列表
     *
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Foundation\Application
     */
    public function index(Request $request)
    {
        $list = ApplicationService::getPageData($request->all());

        return CustomResponse::success($list);
    }

    /**
     * 获取顶级菜单列表
     *
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Foundation\Application
     */
    public function getApplicationCategory(Request $request)
    {
        $appInfo = ApplicationService::getInfo($request->input('appid'));
        $install_category = explode(',', $appInfo->install_category);

        $sysMapInfo = SysMapService::infoByCode('install_category');
        $list = SysMapService::getData([
            'map_code' => $install_category,
            'parent_val' => $sysMapInfo->id,
        ]);

        $type = $request->input('ctype', '1');
        // 列表数据
        if ($type == 1) {
            $returnArray = [];

            // 递归函数，用于构建菜单层次结构
            function buildMenu($items, $parent_id = 0, $prefix = '')
            {
                $result = [];
                $totalItems = count($items);
                foreach ($items as $index => $item) {
                    $label = ($index === $totalItems - 1) ? $prefix.'└ '.$item->map_name : $prefix.'├ '.$item->map_name;
                    if ($item->parent_id == $parent_id) {
                        $result[] = [
                            'label' => $label,
                            'value' => $item->id,
                        ];
                        // 递归调用，为下级菜单项添加适当的前缀
                        $children = buildMenu($items, $item->id, $prefix.'│ ');
                        $result = array_merge($result, $children);
                    }
                }

                return $result;
            }

            $returnArray = buildMenu($list);

            array_unshift($returnArray, ['label' => '顶级', 'value' => 0]);

            return CustomResponse::success($returnArray);
        } elseif ($type == 2) {
            // 表单多选
            $returnArray = [];
            // 递归函数，用于构建菜单层次结构
            function buildMenu($items, $parent_id = 0)
            {
                $result = [];
                foreach ($items as $item) {
                    if ($item->parent_id == $parent_id) {
                        $children = buildMenu($items, $item->id);

                        $menu = [
                            'value' => $item->id,
                            'label' => $item->map_name,
                        ];

                        if (! empty($children)) {
                            $menu['children'] = $children;
                        }
                        $result[] = $menu;
                    }
                }

                return $result;
            }

            $returnArray = buildMenu($list);

            return CustomResponse::success($returnArray);
        }
    }

    /**
     * 获取顶级菜单列表
     *
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Foundation\Application
     */
    public function getApplication(Request $request)
    {
        $list = ApplicationService::getData($request->all());

        $type = $request->input('ctype', '1');
        // 列表数据
        if ($type == 1) {
            $returnArray = [];

            // 递归函数，用于构建菜单层次结构
            function buildMenu($items, $parent_id = 0, $prefix = '')
            {
                $result = [];
                $totalItems = count($items);
                foreach ($items as $index => $item) {
                    $label = ($index === $totalItems - 1) ? $prefix.'└ '.$item->name : $prefix.'├ '.$item->name;
                    if ($item->parent_id == $parent_id) {
                        $result[] = [
                            'label' => $label,
                            'value' => $item->id,
                        ];
                        // 递归调用，为下级菜单项添加适当的前缀
                        $children = buildMenu($items, $item->id, $prefix.'│ ');
                        $result = array_merge($result, $children);
                    }
                }

                return $result;
            }

            $returnArray = buildMenu($list);

            array_unshift($returnArray, ['label' => '顶级', 'value' => 0]);

            return CustomResponse::success($returnArray);
        } elseif ($type == 2) {
            // 表单多选
            $returnArray = [];
            // 递归函数，用于构建菜单层次结构
            function buildMenu($items, $parent_id = 0)
            {
                $result = [];
                foreach ($items as $item) {
                    if ($item->parent_id == $parent_id) {
                        $children = buildMenu($items, $item->id);

                        $menu = [
                            'image' => $item->logo,
                            'value' => $item->id,
                            'label' => $item->name,
                        ];

                        if (! empty($children)) {
                            $menu['children'] = $children;
                        }
                        $result[] = $menu;
                    }
                }

                return $result;
            }

            $returnArray = buildMenu($list);

            return CustomResponse::success($returnArray);
        }
    }

    /**
     * 创建/编辑
     *
     * @param  Request  $request
     * @return void
     */
    public function store(ApplicationRequest $request)
    {
        if ($request->input('id')) {
            // 编辑
            $requestAll = $request->all(['id', 'logo', 'install_category', 'name', 'remark', 'module', 'status']);

            $id = ApplicationService::edit($requestAll['id'], $requestAll);
            if ($id) {
                return CustomResponse::success($id, '编辑成功');
            } else {
                return CustomResponse::error('编辑失败');
            }
        } else {
            // 创建
            $requestAll = $request->all(['logo', 'install_category', 'name', 'remark', 'module', 'status']);
            $result = ApplicationService::create($requestAll);
            if ($result) {
                return CustomResponse::success($result->id, '创建成功');
            } else {
                return CustomResponse::error('创建失败');
            }
        }
    }

    /**
     * 删除
     *
     * @return void
     */
    public function destroy(Request $request, $id)
    {
        $id = ApplicationService::destroy(explode(',', $id));
        if ($id) {
            return CustomResponse::success($id, '删除成功');
        } else {
            return CustomResponse::error('删除失败');
        }
    }

    /**
     * 创建应用模板
     * User: zhx
     * Date: 2023/10/30 0030
     * Time: 13:49
     */
    public function createTpl(Request $request, $id)
    {
        $info = ApplicationService::getInfo($id);

        /**********************************************************/
        // 生成模板
        /**********************************************************/
        // 通过 Artisan 命令生成模板，并传递参数
        Artisan::call('module:make', [
            'name' => $info->module,
            '--option' => 'value', // 可以根据需要传递其他参数
        ]);

        // 获取命令输出
        $output = Artisan::output();

        // 获取生成的模块目录路径
        $moduleDirectory = base_path("modules/{$info->module}");
        // 检查生成的模块目录是否存在
        if (file_exists($moduleDirectory)) {
            return CustomResponse::success('生成成功');
        } else {
            return CustomResponse::error('生成失败');
        }
    }
}
